package view;

import common.Util;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog_content.html")
public class BlogContentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        //1.检测当前是否为已登录状态，如果未登录则重定向到登陆页面
        User user = Util.checkLoginStatus(req);
        if(user==null){
            System.out.println("当前用户未登录");
            resp.sendRedirect("login.html");
            return;
        }

        //2.获取到blogId参数
        String blogId = req.getParameter("blogId");
        if(blogId==null||"".equals(blogId)){
            String html = "<h3>blogId缺失</h3>";
            resp.getWriter().write(html);
            return;
        }

        //3.根据blogId从数据库里查询
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            String html = "<h3>博客不存在</h3>";
            resp.getWriter().write(html);
            return;
        }


        //4.根据blog对象中的userId去user表中查找作者信息
        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());

        //5.进行页面渲染
        ServletContext context = this.getServletContext();
        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,context);
        webContext.setVariable("blog",blog);
        webContext.setVariable("user",author);
        webContext.setVariable("showDeleteButton",blog.getUserId()== user.getUserId());
        String html = engine.process("blog_content",webContext);
        resp.getWriter().write(html);
    }
}
